package org.thirdeye.me2u;

import org.thirdeye.me2u.constants.ApplicationConstants;

import android.os.Bundle;
import android.app.Activity;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;

public class Thirdeye_Me2U extends Activity {

	private TextToSpeech tts = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_thirdeye__me2_u);
		initializeApp();
	}

	private void initializeApp() {
		tts = new TextToSpeech(this, onInitListener);
		EditText editText = (EditText) findViewById(R.id.mainEditText);
		initializeEditText(editText);
		initializeButtons(editText);
	}

	private void initializeEditText(final EditText editText) {
		editText.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View paramView, int paramInt,
					KeyEvent paramKeyEvent) {
				if (paramKeyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER
						&& paramKeyEvent.getAction() == KeyEvent.ACTION_DOWN) {
					speakText(editText);
				}
				return false;
			}
		});
	}

	private void initializeButtons(final EditText editText) {
		Button speakButton = (Button) findViewById(R.id.speak_bn);
		Button clearButton = (Button) findViewById(R.id.clear_bn);
		speakButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				speakText(editText);
			}

		});
		clearButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				editText.setText(ApplicationConstants.EMPTY_STRING);
			}
		});
	}

	private void speakText(final EditText editText) {
		String txtContent = editText.getText().toString();
		tts.speak(txtContent, 0, null);
	}

	private TextToSpeech.OnInitListener onInitListener = new TextToSpeech.OnInitListener() {
		@Override
		public void onInit(int status) {
		}
	};

	@Override
	protected void onDestroy() {
		stopTTS();
		tts.shutdown();
		super.onDestroy();
	}

	private void stopTTS() {
		try {
			if (tts.isSpeaking()) {
				tts.stop();
			}
		} catch (Exception e) {
			Log.e("Exception while Stopping", e.getMessage());
		}
	}

}
